import axios from 'axios'
import { useUserStore } from '../store/user'

const instance = axios.create({
  baseURL: 'http://localhost:3000'
})

// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token')
    if (token) {
      // 如果 localStorage 中有 token，则在请求时带上
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
instance.interceptors.response.use(
  (response) => {
    const { data } = response
    console.log(data)
    if (data && data.message === 'token已过期') {
      localStorage.removeItem('token')
      const userStore = useUserStore()
      userStore.user.isLogin = false
    }
    // 如果响应数据中有 token，则应该将其存储到 localStorage
    if (data.data && data.data.token) {
      localStorage.setItem('token', data.data.token)
    }
    return data
  },
  (error) => {
    return Promise.reject(error)
  }
)

export default instance
